package com.oneandone.httpserver.tcp.http.response;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.TimeZone;

import java.io.InputStream;

import org.apache.log4j.Logger;

/**
 * @author calin
 */
public class BasicHttpResponseSerializer implements HttpResponseSerializer {
	private static final Logger LOGGER = Logger.getLogger(BasicHttpResponseSerializer.class);
	private String CRLF = "\r\n";
	private String LF = "\n";
	
    @Override
    public void serialize(HttpResponse httpResp, OutputStream stream) {
    	LOGGER.debug("Serializing the HTTP Response");
    	String response = new String();
    	// Adding status
    	response += "HTTP/1.1 " + httpResp.getStatus().getStatus() + CRLF;
    	response += "Date: " + getServerTime() + CRLF;
    	//Adding headers
    	Map<String, List<String>> headers = httpResp.getHeaders();
    	Set<String> keySet = headers.keySet();
    	for (String key : keySet){
    		String value = new String();
    		for (String s : headers.get(key))
    			value += s;
    		if (key.contains("-")){
    			String newKey = new String();
    			String[] keyWords = key.split("-");
    			for (int i = 0; i < keyWords.length; i++) {
    	   			String word = keyWords[i];
    				word = word.substring(0, 1).toUpperCase() + word.substring(1);
        			if (i != keyWords.length - 1){
        				newKey += word + "-";
        			}
        			else{
        				newKey += word;
        			}
				}
    			response += newKey + ": " + value + CRLF;
    		}
    		else{
    			key = key.substring(0, 1).toUpperCase() + key.substring(1);
    			response += key + ": " + value + CRLF;
    		}
    		
    	}
    	
    	// Adding body (if exists) and writing response
    	try {
    		if (httpResp.getBody() != null){
    	    	InputStream body = httpResp.getBody();
    	    	response += CRLF;
				byte[] buffer = new byte[1024];
    	    	String msg = new String();
				while (body.available() > 0) {
					int length = body.read(buffer);
					msg += new String(buffer, 0, length);
					response += msg;
					response += CRLF;
				}
			}
			LOGGER.debug("Serialization successfull.Sending the response");
    		stream.write(response.getBytes());
		} 
		catch (IOException e1) {
			e1.printStackTrace();
		}
    	
    }
    
    public String getServerTime() {
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat dateFormat = new SimpleDateFormat(
            "EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
        dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
        return dateFormat.format(calendar.getTime());
    }
}
